<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-02-07
 * Time: 13:48
 */

namespace app\api\model;

use app\api\service\Token as TokenService;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use think\Db;

class User extends BaseModel
{
    protected $table = 'we_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 根据openid获取用户信息
    public static function getByOpenID($openid){
        $user = self::where('openid','=',$openid)->find();
        return $user;
    }

    public function orders()
    {
        return $this->hasMany('Order', 'user_id', 'id');
    }

    public function address()
    {
        return $this->hasOne('UserAddress', 'user_id', 'id');
    }

    // 每点击抽奖一次，数据库抽奖次数减一
    public static function reduceLotteryCount(){
        $uid = TokenService::getCurrentUid();
        if(!$uid){
            throw new UserException();
        }
        Db::startTrans();
        try{
            $user = self::get($uid);
            $lottery_count = $user->lottery_count - 1;
            $user->lottery_count = $lottery_count;
            $user->save();
            Db::commit();
            return json(new SuccessMessage([
                'code' => 200,
                'msg' => '抽奖次数更新成功'
            ]),200);
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }

}